﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Rsa.DataAccess.Models;
using Rsa.DataAccess;
using System.Configuration;
using Rsa.Models;
using System.Web.Security;
using System.Data.SqlClient;

namespace Rsa.Controllers {
    public class InicioController : Controller {
        UsuarioDa da = new UsuarioDa(ConfigurationManager.ConnectionStrings["RsaDb"].ConnectionString);
        //
        // GET: /Usuario/
        public ActionResult Index() {
            if (Request.IsAuthenticated) {
                return RedirectToAction("Index", "Usuario");
            }
            
            SelectList sexos = new SelectList(new [] {
                new {Id = 1, Nombre = "Masculino"},
                new {Id = 2, Nombre = "Femenino"}
            }, "Id", "Nombre", 0);

            ViewBag.Sexos = sexos;
            return View();
        }

        public ActionResult Registro() {
            return View("Index");
        }

        [HttpPost]
        public ActionResult Registro(Usuario usuario) {
            if(ModelState.IsValid) {
                da.AdicionarUsuario(usuario);
            }
            
            return RedirectToAction("Index", "Inicio");
        }

        [HttpPost]
        public ActionResult Login(LoginViewModel login, string returnUrl) {
            if (ModelState.IsValid) {
                if (Membership.ValidateUser(login.LoginUsername, login.LoginPassword)) {
                    FormsAuthentication.SetAuthCookie(login.LoginUsername, true);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) {
                        return Redirect(returnUrl);
                    }
                    else {
                        return RedirectToAction("Index", "Usuario");
                    }
                }
                else {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            return View(login);
        }
    }
}
